﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace DomainModel
{
    public class XMLModelSerialization
    {
        public XElement save(ISmartNoteModel model)
        {
            XElement root = new XElement("tagNote");

            XElement tags = new XElement("tags");
            saveTags(model, tags, 0);
            root.Add(tags);

            XElement notes = new XElement("notes");
            saveNotes(model, notes);
            root.Add(notes);

            return root;
        }

        public void load(XElement xml, ISmartNoteModel model)
        {

        }

        void saveTags(ISmartNoteModel model, XElement tags, int parentTag)
        {
            foreach (Tag tag in model.getChildrenTags(parentTag))
            {
                tags.Add(new XElement("tag", new[] { 
                    new XAttribute("id", tag.Id), 
                    new XAttribute("name", tag.Name),
                    new XAttribute("parentId", parentTag)
                })); ;
                saveTags(model, tags, tag.Id);
            }
        }

        void saveNotes(ISmartNoteModel model, XElement notes)
        {
            foreach (Note note in model.findNotes(0))
            {
                XElement noteTag = new XElement("note");
                noteTag.Add(new XAttribute("id", note.Id));
                noteTag.Add(new XElement("text", note.Text));

                XElement tags = new XElement("tags");
                foreach (Tag tag in model.getTags(note.Id))
                {
                    tags.Add(new XElement("tag", new XAttribute("id", tag.Id)));
                }

                notes.Add(noteTag);
            }
        }
    }
}
